<template>
  <div>
    <div>
      <!-- 答案信息表单 -->
      <FormPanel ref="formPanel" :list="formList" formType="add" labelWidth="100" :isSubmitBtn="false" @formChange="formChangeHandle" />

      <!-- 问题组表格 -->
      <FilterTable
        ref="table"
        :columns="questionColumns"
        :isPagination="false"
        :isToperInfo="false"
        :isSelectColumn="false"
        :isColumnFilter="false"
        :dataSource="questionList"
        columnsRef="wjdyWjxzWtzTable"
        :onColumnsChange="columns => (this.questionColumns = columns)"
      >
        <template slot="controls">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addQuestion">选择问题</el-button>
        </template>
      </FilterTable>
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button @click="closeDrawer(false)">取 消</el-button>
      <el-button @click="commit" type="primary" :loading="loginBtnState">提 交</el-button>
    </div>

    <!-- 问题选择弹框 -->
    <BaseDialog :visible.sync="dialogVisible" title="问题选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '10px' }" destroyOnClose>
      <problemSelect @fatherReq="reqProblem" @fatherGoBack="goBackProblem" />
    </BaseDialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import moment from 'moment';
import * as types from '@/api/customerCare/visitRules/questionnaireMake/types';
import { editQuestionnaireInfo , saveQuestionnaire, getQuestionnaireEditInfo, queryQuestionByQuestionnaireId } from '@/api/customerCare/visitRules/questionnaireMake';
import { dictionary } from '@/utils/dictMixin';
import problemSelect from '../components/problemSelect';

export default {
  name: 'QuestionnairePanel',
  mixins: [dictionary],
  props: {
    questionnaireId: String,
    type: String,
    recordVersion: String
  },
  components: {
    problemSelect
  },
  data() {
    this.BaseTable = null;
    return {
      formList: this.createFormList(), //问卷表单
      questionList: [], //问题表格List
      questionColumns: this.createQuestionColumns(), //问题表格列
      isSaveTemplate: false, //是否保存为模板
      dialogVisible: false, //是否显示答案选择dia
      chooseAnswerIndex: -1, //当前正在进行选择答案的行
      templageDialogVisible: false //是否显示选择模板dia
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    loginBtnState() {
      return this.btnLoading[types.SAVE];
    }
  },
  methods: {
    //获取问卷信息
    async getQuestionnaire() {
      if (this.questionnaireId && this.questionnaireId.length > 0 && this.type != 'add') {
        const res = await getQuestionnaireEditInfo({questionnaireId:this.questionnaireId});

        if (res.resultCode == 200) {
          this.questionnaire = res.data;
        } else {
          this.$message.error('获取问卷信息失败');
          return;
        }

        const listRes = await queryQuestionByQuestionnaireId({
          questionnaireId: this.questionnaireId,
          limit: 9999,
          pageNum: 1
        });

        if (listRes.resultCode == 200) {
          this.questionList = listRes.data.records;
        } else {
          this.$message.error('获取问题列表失败');
          return;
        }
      } else {
        this.questionnaire = {
          questionnaireName: '',
          questionnaireType: '',
          isValid: 10041002, //是
          dataSources: 10451001, //店端
          isTemplate: 10041002 //问卷
        };
        this.questionList = [];
      }
      this.formList[0].initialValue = this.questionnaire.questionnaireName;
      this.formList[1].initialValue = this.questionnaire.questionnaireType;
      this.formList[2].initialValue = this.questionnaire.isValid;
      this.formList[3].initialValue = this.questionnaire.dataSources;
      this.formList = [...this.formList];
      this.questionList = [...this.questionList];
    },
    //问卷表单列
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '问卷名称',
          fieldName: 'questionnaireName',
          disabled: this.type == 'edit',
          rules: [{ required: true, message: '请填写问卷名称', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '问卷类型',
          fieldName: 'questionnaireType',
          itemList: this.createDictList('1572'),
          rules: [{ required: true, message: '请选择问卷类型', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '是否启用',
          fieldName: 'isValid',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '请选择是否启用', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'dataSources',
          itemList: this.createDictList('1045'),
          disabled: true
        }
      ];
    },
    //关闭drawer
    closeDrawer(refresh) {
      if (refresh) {
        this.$emit('changeHandle', { dataSources: 10451001 });
      }
      this.$emit('close', false);
    },
    //问题表格列
    createQuestionColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.delQuestion(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '问题ID',
          dataIndex: 'questionId',
          showOverflowTooltip: true,
          editType: 'input',
          editRequired: true
        },
        {
          title: '问题名称',
          dataIndex: 'questionName',
          showOverflowTooltip: true,
          editType: 'input',
          editRequired: true
        },
        {
          title: '问题内容',
          dataIndex: 'questionContent',
          showOverflowTooltip: true,
          editType: 'input',
          editRequired: true,
          defaultEditable: true
        },
        {
          title: '问题类型',
          dataIndex: 'questionType',
          editType: 'select',
          editRequired: true,
          editItems: this.createDictList('1571')
        },
        {
          title: '是否必填',
          dataIndex: 'isMustFilled',
          editType: 'select',
          editRequired: true,
          editItems: this.createDictList('1004')
        },
        {
          title: '排列顺序',
          dataIndex: 'questionSortNum',
          width: 80,
          editable: true,
          editType: 'input',
          editRequired: true,
          editPattern: /^[0-9]+$/
        }
      ];
    },
    //新增问题
    addQuestion() {
      this.dialogVisible = true;
    },
    //删除问题
    delQuestion(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.questionList.splice(row.$index, 1);
      });
    },
    //点击提交
    commit() {
      //调用表单验证
      this.$refs.formPanel.SUBMIT_FORM();
    },
    //表单验证回调，传回表单参数
    formChangeHandle(val) {
      if (this.questionList.length === 0) {
        this.$message.info('请添加问题信息');
        return;
      }
      let a = true;
      for (let i = 0; i < this.questionList.length; i++) {
        if (this.questionList[i].questionName == '' || this.questionList[i].questionName == null || this.questionList[i].questionName == undefined) {
          this.$message({
            type: 'error',
            message: '第' + (i + 1) + '行问题名称不能为空!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].questionContent == '' || this.questionList[i].questionContent == null || this.questionList[i].questionContent == undefined) {
          this.$message({
            type: 'error',
            message: '第' + (i + 1) + '行问题内容不能为空!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].questionType == '' || this.questionList[i].questionType == null || this.questionList[i].questionType == undefined) {
          this.$message({
            type: 'error',
            message: '第' + (i + 1) + '行问题类型不能为空!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].isMustFilled == '' || this.questionList[i].isMustFilled == null || this.questionList[i].isMustFilled == undefined) {
          this.$message({
            type: 'error',
            message: '第' + (i + 1) + '行是否必填不能为空!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].questionSortNum == '' || this.questionList[i].questionSortNum == null || this.questionList[i].questionSortNum == undefined) {
          this.$message({
            type: 'error',
            message: '第' + (i + 1) + '行排列顺序不能为空!'
          });
          a = false;
          break;
        }
      }
      if (a) {
        this.questionnaire.isValid = val.isValid;
        this.questionnaire.questionnaireName = val.questionnaireName;
        this.questionnaire.questionnaireType = val.questionnaireType;
        this.questionnaire.questionList = this.questionList;
        if(this.type === "add"){
          saveQuestionnaire(this.questionnaire).then(res => {
            if (res.resultCode === 200) {
              this.$message.success('保存成功');
              this.closeDrawer(true);
            } else {
              this.$message.error('保存失败');
            }
          });
        }else{
          this.questionnaire.questionnaireId = this.questionnaireId;
          this.questionnaire.recordVersion = this.recordVersion;
          editQuestionnaireInfo(this.questionnaire).then(res => {
            if (res.resultCode === 200) {
              this.$message.success('保存成功');
              this.closeDrawer(true);
            } else {
              this.$message.error('保存失败');
            }
          });
        }
      }
    },
    //选择模板
    chooseTemplage() {
      this.templageDialogVisible = true;
    },
    //打开选择答案dia
    openDia(row) {
      this.dialogVisible = true;
      this.chooseAnswerIndex = row.$index;
    },
    //清除选择的问题
    delAnswer(row) {
      if (this.chooseAnswerIndex !== -1) {
        this.$set(this.questionList[this.chooseAnswerIndex], 'answerGroupId', '');
        this.$set(this.questionList[this.chooseAnswerIndex], 'answerGroupName', '');
        this.$set(this.questionList[this.chooseAnswerIndex], 'answer', '');
      }
    },
    //取消选择问题
    goBackProblem() {
      this.dialogVisible = false;
    },
    //确定选择问题
    reqProblem(data) {
      for(var i=0;i<data.length;i++){
        let vat = {
          questionId: data[i].questionId,
          questionName: data[i].questionName,
          questionContent: data[i].questionContent,
          questionType: data[i].questionType,
          isMustFilled: data[i].isMustFilled,
          questionSortNum: this.questionList.length+1
        };
        this.questionList.push(vat);
      }

      this.goBackProblem();
    }
  },
  created() {
    this.getQuestionnaire();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  }
};
</script>
<style scoped>
.cover-container {
  width: 1100px !important;
}
</style>
